import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:signage/app/routes/app_pages.dart';
import 'package:signage/app/utils/sp_util.dart';
import 'package:signage/app/utils/toast_utils.dart';
import 'package:signage/app/utils/http_client.dart';
import 'package:signage/l10n/l10n.dart';

class RegisterController extends GetxController {
  //TODO: Implement RegisterController
final HttpClient _httpClient = HttpClient();
  
  // 手机号输入控制
  final phoneNumber = ''.obs;
  // 验证码输入控制
  final verificationCode = ''.obs;
  // 是否同意协议
  final agreedToTerms = false.obs;
  // 获取验证码按钮状态
  final canGetCode = true.obs;
  // 倒计时秒数
  final countdown = 0.obs;

  // 验证手机号格式
  bool isPhoneValid() {
    return phoneNumber.value.length == 11;
  }

  // 验证是否可以登录
  bool canLogin() {
    return isPhoneValid() && 
           verificationCode.value.length == 6 && 
           agreedToTerms.value;
  }

  // 获取验证码
  Future<void> getVerificationCode() async {
    if (!isPhoneValid() || !canGetCode.value) return;
    
    try {
      EasyLoading.show();
      await _httpClient.getCaptcha(mobile: phoneNumber.value);
      // 开始倒计时
      startCountdown();
    } catch (e) {
      ToastUtils.showError(e.toString());
    } finally {
      EasyLoading.dismiss();
    }
  }

  // 倒计时逻辑
  void startCountdown() {
    countdown.value = 60;
    canGetCode.value = false;
    
    Future.doWhile(() async {
      await Future.delayed(const Duration(seconds: 1));
      countdown.value--;
      if (countdown.value <= 0) {
        canGetCode.value = true;
        return false;
      }
      return true;
    });
  }

  // 登录方法
  Future<void> login() async {
    if (!canLogin()) return;
    EasyLoading.show();
    try {
      final response = await _httpClient.register(
        mobile: phoneNumber.value,
        captcha: verificationCode.value,
      );
      
      if (response.code == 200) {
        await SpUtil.saveUid(response.id ?? '');
        await SpUtil.setString('token', response.token ?? '');
        Get.offAllNamed(Routes.HOME);
      } else {
        ToastUtils.showError(response.msg ?? AppLocalizations.of(Get.context!)!.translate('unknown_error'));
      }
    } catch (e) {
      Get.snackbar(
        AppLocalizations.of(Get.context!)!.translate('error'),
        e.toString()
      );
    } finally {
      EasyLoading.dismiss();
    }
  }
}
